package v1

import (
	"github.com/sirupsen/logrus"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

const (
	FieldsPrefix = "prefix"
)

type Logger interface {
	Debugf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Warnf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
}

var (
	prefix string
	format string
	logger *logrus.Entry
)

func InitFlags(flags *pflag.FlagSet) {
}

func ViperConfig(flags *viper.Viper) {

}

func InitViper(flags *viper.Viper) {

}

func OptionConfig(opts ...option) {
	for _, apply := range opts {
		apply(logger)
	}
}

func Initialize(opts ...option) {
	//logrus.SetFormatter(&logrus.TextFormatter{
	//	ForceColors:   true,
	//	DisableColors: false,
	//	ForceQuote: true,
	//	DisableQuote: false,
	//	PadLevelText: true,
	//	EnvironmentOverrideColors: true,
	//})

	for _, apply := range opts {
		apply(logger)
	}

	logrus.Infof("format %v", format)
	switch format {
	case "text":
		logrus.SetFormatter(&logrus.TextFormatter{
			ForceColors:               true,
			DisableColors:             false,
			ForceQuote:                true,
			DisableQuote:              false,
			PadLevelText:              true,
			EnvironmentOverrideColors: true,
		})
		logger = logrus.WithFields(logrus.Fields{
			FieldsPrefix: prefix,
		})
	case "json":
		logrus.SetFormatter(&logrus.JSONFormatter{})
		logger = logrus.WithFields(logrus.Fields{
			FieldsPrefix: prefix,
		})
	}

	logger.Infof("%v initialized", prefix)
}

func Close() error {
	logger.Infof("%v closed", prefix)
	return nil
}

func NewLogger(prefix string) *logrus.Entry {
	logrus.SetLevel(logrus.DebugLevel)
	return logrus.WithFields(logrus.Fields{
		FieldsPrefix: prefix,
	})
}

func Debugf(format string, args ...interface{}) {
	if logger == nil {
		logrus.Errorf("log should be Initialize")
		return
	}
	logger.Debugf(format, args)
}

func Infof(format string, args ...interface{}) {
	if logger == nil {
		logrus.Errorf("log should be Initialize")
		return
	}
	logger.Infof(format, args)
}

func Warnf(format string, args ...interface{}) {
	if logger == nil {
		logrus.Errorf("log should be Initialize")
		return
	}
	logger.Warnf(format, args)
}

func Errorf(format string, args ...interface{}) {
	if logger == nil {
		logrus.Errorf("log should be Initialize")
		return
	}
	logger.Errorf(format, args)
}

func Fatalf(format string, args ...interface{}) {
	if logger == nil {
		logrus.Errorf("log should be Initialize")
		return
	}
	logger.Fatalf(format, args)
}
